//
//  CXProjectClickViewController.m
//  GiftThat
//
//  Created by ChuXiang on 16/1/11.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "CXProjectClickViewController.h"
#import "SFJumpWebViewController.h"
#import "CXProjectDidClickCollectionViewCell.h"
#import "MLKMenuPopover.h"

#define MENU_POPOVER_FRAME  CGRectMake(self.view.width - 148, 0, 140, 88)

//-------刷新
//限制一次刷新
static int scrolltimes = 0;
//现在数据个数
static int numOfAll = 0;
//-------
static int oldNumOfAll = 0;
static BOOL hideOrApper = YES;


@interface CXProjectClickViewController () <UICollectionViewDelegate, UICollectionViewDataSource, MLKMenuPopoverDelegate>
@property (nonatomic, strong) UICollectionView *myCollection;
@property (nonatomic, strong) NSMutableArray *myData;
@property (nonatomic, strong) NSArray *menuItems;
@property (nonatomic, strong) MLKMenuPopover *menuPopover;
@property (nonatomic, strong) NSString *getDataOfUrl;

//-------刷新
//tableview方向判断
@property (nonatomic, assign) CGFloat contenty;

@end

@implementation CXProjectClickViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.myData = [NSMutableArray arrayWithCapacity:0];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonDidPress:)];
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];

    
    [self createCollection];
    

    
    self.menuItems = [NSArray arrayWithObjects:@"默认排序", @"按热度排序", nil];
    
    //收到删除通知刷新
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(DidPress) name:@"Refresh" object:nil];
    


}

- (void)DidPress {
    [self.myCollection reloadData];
}
#pragma mark - CreateCollection
- (void)createCollection {
    UICollectionViewFlowLayout *FlowLayout = [[UICollectionViewFlowLayout alloc]init];
    FlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    FlowLayout.itemSize = CGSizeMake(self.view.width, self.view.height / 4);
    FlowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    FlowLayout.minimumLineSpacing = CGFLOAT_MIN;
    self.myCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 113) collectionViewLayout:FlowLayout];
    self.myCollection.delegate = self;
    self.myCollection.dataSource = self;
    self.myCollection.backgroundColor = [UIColor whiteColor];
    [self.myCollection registerClass:[CXProjectDidClickCollectionViewCell class] forCellWithReuseIdentifier:@"CXProjectDidClickCollectionViewCellIdentifier"];
    self.myCollection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myCollection];

}
#pragma mark - 传入id
- (void)setGetUrlId:(NSString *)getUrlId WithTypeId:(NSString *)typeId WithTitle:(NSString *)title {
    if (getUrlId && typeId && title) {
        if ([typeId isEqualToString:@"1"]) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Sort"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonDidPress:)];
        }
        self.typeId = typeId;
        self.getUrlId = getUrlId;
        self.title = title;
        NSString *str = nil;
        if ([self.typeId isEqualToString:@"1"]) {
            str = [NSString stringWithFormat:kClassFicationOnePageTopGetURL, getUrlId];
            [self getDataWith:str withOffset:@"0"];
        }else{
            str = [NSString stringWithFormat:kClassFicationOnePageDownGetURL, getUrlId];
            [self getData:str withOffset:@"0"];
        }

        self.navigationItem.title = self.title;
    }
}



#pragma mark - GetData
- (void)getDataWith:(NSString *)url withOffset:(NSString *)offset{
    NSString *getUrl = [NSString stringWithFormat:@"%@%@", url, offset];

    [CXNetWorkTool getWithUrl:getUrl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        if (result) {
            NSDictionary *data = result[@"data"];
            NSArray *array = data[@"items"];
            for (NSDictionary *dic in array) {
                SFSelectionCellModel *model = [[SFSelectionCellModel alloc] initWithDictionary:dic];
                [self.myData addObject:model];
            }
            scrolltimes = 0;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myCollection reloadData];
            });
        }
    } fail:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark -GetDataSource
- (void)getData:(NSString *)url  withOffset:(NSString *)offset {
    
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@", url, offset];
    
    [CXNetWorkTool getWithUrl:getUrl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        if (result) {
            NSDictionary *data = result[@"data"];
            NSArray *array = data[@"posts"];
            for (NSDictionary *dic in array) {
                SFSelectionCellModel *model = [[SFSelectionCellModel alloc] initWithDictionary:dic];
                [self.myData addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myCollection reloadData];
            });
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}


#pragma mark - CollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.myData.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CXProjectDidClickCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXProjectDidClickCollectionViewCellIdentifier" forIndexPath:indexPath];
    cell.SelectionCellModel = self.myData[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SFSelectionCellModel *model = self.myData[indexPath.item];
    SFJumpWebViewController *JumpWebView = [[SFJumpWebViewController alloc]initWithURL:model.content_url];
    [self.navigationController pushViewController:JumpWebView animated:YES];
    CATransition *animation = [CATransition animation];
    animation.duration = 1.5f;
    [animation setType:@"kCATransitionFade"];
    
    [self.navigationController.view.layer addAnimation:animation forKey:nil];

}

#pragma mark - RightButtonDidPress
- (void)rightBarButtonDidPress:(UIBarButtonItem *)sender {
    
    if (hideOrApper) {
        [self.menuPopover dismissMenuPopover];
        
        self.menuPopover = [[MLKMenuPopover alloc] initWithFrame:MENU_POPOVER_FRAME menuItems:self.menuItems];
        
        self.menuPopover.menuPopoverDelegate = self;
        [self.menuPopover showInView:self.view];
    }else {
        [self.menuPopover dismissMenuPopover];
    }
    hideOrApper = !hideOrApper;

}

- (void)menuPopover:(MLKMenuPopover *)menuPopover didSelectMenuItemAtIndex:(NSInteger)selectedIndex{
    hideOrApper = !hideOrApper;

    self.typeId = @"1";
    [self.menuPopover dismissMenuPopover];
    [self.myData removeAllObjects];
    if (selectedIndex == 0) {
        self.getDataOfUrl = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?limit=20&offset=0", self.getUrlId];
        [self getDataWith:self.getDataOfUrl withOffset:@""];
        [self.myCollection reloadData];
        
    }else if (selectedIndex == 1) {
        self.getDataOfUrl = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?limit=20&offset=0&order_by=likes_count", self.getUrlId];
        [self getDataWith:self.getDataOfUrl withOffset:@""];
        [self.myCollection reloadData];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([self.typeId isEqualToString:@"1"]) {
        if (scrollView.contentOffset.y > self.contenty) {
            if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
                //加载更多数据
                if (scrolltimes == 0) {
                    numOfAll += 20;
                    NSString *str = [NSString stringWithFormat:@"offset=%d", oldNumOfAll];
                    NSString *str1 = [NSString stringWithFormat:@"offset=%d",numOfAll];
                    self.getDataOfUrl = [self.getDataOfUrl stringByReplacingOccurrencesOfString:str withString:str1];

                    [self getDataWith:self.getDataOfUrl withOffset:@""];
                    scrolltimes = 1;
                    oldNumOfAll = numOfAll;
                }
            }
        }
    }
}




#pragma mark - LeftButtonDidPress
- (void)leftButtonDidPress:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
